/*
 * ListTreeNode.java
 */

package xq.ide.node;

import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import javax.swing.tree.TreeNode;

/**
 *
 * @author ThorntonRP
 */
public class ListTreeNode extends DataTreeNode {
	
	private final Collection collection;
	private String nodeName;

	public ListTreeNode(DataTreeNode parentNode, String nodeName, Object nodeData, int nodeIndex) {
		super(parentNode, nodeData, nodeIndex);
		this.nodeName = nodeName;
		this.collection = (Collection) nodeData;
	}

	@Override
	public TreeNode getChildAt(int childIndex) {
		Iterator it = collection.iterator();
		Object childData = null;
		for (int i = 0; i < childIndex; i++) {
			childData = it.next();
		}
		if (childData instanceof Collection) {
			return new ListTreeNode(this, childData.getClass().getSimpleName(), childData, childIndex);
		} else {
			return new BeanTreeNode(this, childData, childIndex);
		}
	}

	@Override
	public int getChildCount() {
		return collection.size();
	}

	@Override
	public boolean getAllowsChildren() {
		return collection.size() > 0;
	}

	@Override
	public boolean isLeaf() {
		return collection.size() == 0;
	}

	@Override
	public Enumeration children() {
		return new Enumeration() {
			Iterator it = collection.iterator();
			int index = 0;
			@Override
			public boolean hasMoreElements() {
				return it.hasNext();
			}

			@Override
			public Object nextElement() {
				it.next();
				return getChildAt(index++);
			}
		};
	}

	@Override
	public String toString() {
		return nodeName;
	}
}
